const express = require("express");
const app = express();
const cors = require("cors");
const joi = require("@hapi/joi");
const config = require("./config/config");
const expressJWT = require("express-jwt");

/* router导入 */
const userinfoRouter = require("./router/userinfoRouter");
const userRouter = require("./router/userRouter");
const artcateRouter = require("./router/artcate");
const articleRouter = require("./router/article");
const getMenu = require("./router/menu");
app.use(cors());
app.use(express.urlencoded({ extended: false }));

app.use(function (req, res, next) {
  res.cc = function (err, status = 1) {
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
    });
  };
  next();
});
app.use((err, req, res, next) => {
  if (err instanceof joi.ValidationError) return res.cc(err);
  res.cc(err);
});
app.use(
  expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api\//] })
);
app.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError") return res.cc("身份认证失败");
});
app.use("/api", userRouter);
app.use("/my", userinfoRouter);
app.use("/my/article", artcateRouter);
app.use("/my/articles", articleRouter);
app.use("/menu", getMenu);
app.use("/uploads", express.static("./uploads"));
app.listen(3000, () => {
  console.log("http://127.0.0.1:3000");
});
